package top.yongyan0624.controller;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import top.yongyan0624.common.lang.Result;
import top.yongyan0624.entity.ItemBorrow;
import top.yongyan0624.entity.ItemBorrowUser;
import top.yongyan0624.entity.PropertyPay;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author yongyan
 * @since 2021-09-12
 */
@RestController
@RequestMapping("/item/borrow")
public class ItemBorrowController extends BaseController {
    @GetMapping("/list")
    public Result list(String title) {
        Page<ItemBorrow> pageData = itemBorrowService.page(getPage(), new QueryWrapper<ItemBorrow>()
                .like(StrUtil.isNotBlank(title), "title", title).orderByDesc("create_time"));

        pageData.getRecords().forEach(i -> {
            i.setUser(sysUserService.getById(i.getUserId()));
            i.setImgList(StrUtil.split(i.getImg(), ',', true, true));
        });

        return Result.success(pageData);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        ItemBorrow itemBorrow = itemBorrowService.getById(id);

        itemBorrow.setUser(sysUserService.getById(itemBorrow.getUserId()));
        itemBorrow.setImgList(StrUtil.split(itemBorrow.getImg(), ',', true, true));

        return Result.success(itemBorrow);
    }

    @GetMapping("/listByUserId")
    public Result listByUserId(String title, String userId) {
        Page<ItemBorrow> pageData = itemBorrowService.page(getPage(), new QueryWrapper<ItemBorrow>()
                .eq("user_id", userId).like(StrUtil.isNotBlank(title), "title", title)
                .orderByDesc("create_time"));

        pageData.getRecords().forEach(i -> {
            i.setUser(sysUserService.getById(i.getUserId()));
            i.setImgList(StrUtil.split(i.getImg(), ',', true, true));
        });

        return Result.success(pageData);
    }

    @GetMapping("/listByLease")
    public Result listByLease(String title, String userId) {
        Page<ItemBorrowUser> pageData = itemBorrowUserService.page(getPage(), new QueryWrapper<ItemBorrowUser>().eq("user_id", userId));

        //用以存储不符合title模糊查询的item
        List<ItemBorrowUser> delItem = new ArrayList<>();

        pageData.getRecords().forEach(i -> {
            ItemBorrow borrow = itemBorrowService.getById(i.getItemId());
            borrow.setUser(sysUserService.getById(i.getUserId()));
            borrow.setImgList(StrUtil.split(borrow.getImg(), ',', true, true));

            i.setItem(borrow);
            if (title != null && !i.getItem().getTitle().contains(title)) {
                delItem.add(i);
            }

            i.setUser(sysUserService.getById(i.getUserId()));
        });

        //删除所有不符合title的item
        pageData.getRecords().removeAll(delItem);

        return Result.success(pageData);
    }

    @PostMapping("/save")
    public Result save(@RequestPart ItemBorrow itemBorrow, @RequestPart MultipartFile[] imgFiles) {
        try {
            if (imgFiles.length <= 0) {
                return Result.fail("文件为空");
            }
            //文件不为空，处理文件，存储文件并生成随机虚拟路径文件名
            String fileName = handleFile("borrow", itemBorrow.getUserId(), imgFiles);

            //设置img虚拟路径
            itemBorrow.setImg(fileName);

        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return Result.fail("图片上传失败！");
        }

        itemBorrowService.save(itemBorrow);

        itemBorrow.setUser(sysUserService.getById(itemBorrow.getUserId()));
        itemBorrow.setImgList(StrUtil.split(itemBorrow.getImg(), ',', true, true));

        return Result.success(itemBorrow);
    }

    @PostMapping("/update")
    @PreAuthorize("hasAuthority('borrow:update')")
    public Result update(@RequestPart ItemBorrow itemBorrow, @RequestPart MultipartFile[] imgFiles) {
        try {
            if (imgFiles.length > 0) {
                //文件不为空，处理文件，存储文件并生成随机虚拟路径文件名
                String fileName = handleFile("borrow", itemBorrow.getUserId(), imgFiles);

                //设置img虚拟路径
                itemBorrow.setImg(fileName);
            }

        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return Result.fail("图片上传失败！");
        }

        itemBorrowService.updateById(itemBorrow);

        itemBorrow.setUser(sysUserService.getById(itemBorrow.getUserId()));
        itemBorrow.setImgList(StrUtil.split(itemBorrow.getImg(), ',', true, true));

        return Result.success(itemBorrow);
    }

    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('borrow:delete')")
    public Result delete(@RequestBody Long[] ids) {
        itemBorrowService.removeByIds(Arrays.asList(ids));
        itemBorrowUserService.remove(new QueryWrapper<ItemBorrowUser>().in("item_id", ids));

        return Result.success("");
    }

    @PostMapping("/lease")
    public Result lease(@RequestBody ItemBorrowUser itemBorrowUser) {
        ItemBorrow borrow = itemBorrowService.getById(itemBorrowUser.getItemId());

        if (borrow.getAmount() <= 0) {
            throw new RuntimeException("租借物品数量不足");
        }

        borrow.setAmount(borrow.getAmount() - 1);
        itemBorrowService.updateById(borrow);

        itemBorrowUserService.save(itemBorrowUser);

        borrow.setUser(sysUserService.getById(borrow.getUserId()));
        borrow.setImgList(StrUtil.split(borrow.getImg(), ',', true, true));

        itemBorrowUser.setItem(borrow);
        itemBorrowUser.setUser(sysUserService.getById(itemBorrowUser.getUserId()));

        return Result.success(itemBorrowUser);
    }
}
